package org.base.admin.modules.sys.service.impl;


import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.base.admin.modules.sys.service.SysMenuService;
import org.base.dao.modules.base.BaseServiceImpl;
import org.base.dao.modules.sys.mapper.SysMenuDao;
import org.base.dao.modules.sys.model.SysMenuDO;
import org.springframework.stereotype.Service;

@Service
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenuDO, SysMenuDao>implements SysMenuService {
	
	
	@Override
	public List<SysMenuDO> findAdminMenus() {
		List<SysMenuDO> sysMenus = baseDao.findAdminMenus();
		List<SysMenuDO> menus = tree(sysMenus);
		sort(menus);
		return menus;
	}
	
	@Override
	public List<SysMenuDO> findUserMenus(Long userId) {
		List<SysMenuDO> sysMenus = baseDao.findUserMenus(userId);
		List<SysMenuDO> menus = tree(sysMenus);
		sort(menus);
		return menus;
	}
	
	private List<SysMenuDO> tree(List<SysMenuDO> sysMenus){
		Map<Long, List<SysMenuDO>> menuMap = sysMenus.stream().collect(Collectors.groupingBy((m)->{
			return m.getParentId()==null?0L:m.getParentId();
		}));
		List<SysMenuDO> menus = menuMap.get(0L);
		deepTree(menus,menuMap);
		return menus;
	}
	
	private void deepTree(List<SysMenuDO> menus, Map<Long, List<SysMenuDO>> menuMap) {
		if(menus==null)return;
		for(SysMenuDO menu : menus) {
			List<SysMenuDO> ms = menuMap.get(menu.getId());
			if(ms == null)return;
			menu.setChildren(ms);
			deepTree(ms,menuMap);
		}
	}
	
	private void sort(List<SysMenuDO> menus) {
		if(menus==null)return;
		Collections.sort(menus, (m1, m2)->{ 
			return m1.getOrderNum()-m2.getOrderNum();
		});
		for(SysMenuDO menu : menus) {
			List<SysMenuDO> ms = menu.getChildren();
			if(ms == null)continue;
			sort(ms);
		}
		
	}

}
